package cn.knightzz.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.knightzz.constant.RoleType;
import cn.knightzz.entity.SysEvent;
import cn.knightzz.entity.SysFile;
import cn.knightzz.entity.SysUser;
import cn.knightzz.entity.SysUserEvent;
import cn.knightzz.mapper.SysEventMapper;
import cn.knightzz.mapper.SysFileMapper;
import cn.knightzz.mapper.SysUserEventMapper;
import cn.knightzz.service.SysEventService;
import cn.knightzz.service.SysFileService;
import cn.knightzz.service.SysUserEventService;
import cn.knightzz.service.SysUserService;
import cn.knightzz.vo.EventCountVO;
import cn.knightzz.vo.PutEventVO;
import cn.knightzz.vo.UpdateEventVO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author knightzz
 * @since 2021-05-01
 */
@Service
public class SysEventServiceImpl extends ServiceImpl<SysEventMapper, SysEvent> implements SysEventService {

    @Resource
    SysEventMapper eventMapper;

    @Resource
    SysFileService fileService;

    @Resource
    SysUserService userService;

    @Resource
    SysUserEventService userEventService;

    @Resource
    SysUserEventMapper userEventMapper;

    @Override
    public void addEvent(PutEventVO eventVO) {
        SysEvent event = new SysEvent();
        // 拷贝属性
        BeanUtil.copyProperties(eventVO, event, true);
        // 获取用户地址
        SysUser user = userService.getUserById(eventVO.getAuthorId());
        event.setHandleId(eventVO.getAuthorId());
        // 设置辖区
        event.setArea(user.getAddress());
        // 封装文件列表
        String fileList = this.getFileList(eventVO.getFiles());
        event.setFileList(fileList);
        eventMapper.insert(event);
        // 将用户和事件关联
        SysUserEvent userEvent = new SysUserEvent();
        userEvent.setEventId(event.getId());
        userEvent.setUserId(event.getHandleId());
        userEvent.setStatus(1);
        userEventService.addUserEvent(userEvent);
    }

    @Override
    public IPage<SysEvent> selectEventPage(Long pageNum, Long pageSize, String query) {
        Page<SysEvent> page = new Page<>();
        page.setCurrent(pageNum);
        page.setSize(pageSize);
        return eventMapper.selectEvent(page, query);
    }

    // 将列表转换为以,分割的字符串
    private String getFileList(List<Long> files) {
        StringBuffer stringBuffer = new StringBuffer();
        for (Long file : files) {
            stringBuffer.append(file);
            stringBuffer.append(",");
        }
        if (stringBuffer.length() >= 1) {
            // 去除最后一个逗号
            return stringBuffer.substring(0, stringBuffer.length() - 1);
        } else {
            return stringBuffer.toString();
        }
    }

    // 更新事件信息
    @Override
    public Boolean updateEvent(UpdateEventVO eventVO) {

        SysEvent sysEvent = new SysEvent();
        BeanUtil.copyProperties(eventVO, sysEvent, true);
        eventMapper.updateById(sysEvent);

        SysUserEvent sysUserEvent = new SysUserEvent();
        sysUserEvent.setUserId(eventVO.getHandleId());
        sysUserEvent.setEventId(eventVO.getId());
        sysUserEvent.setStatus(eventVO.getStatus());
        userEventService.updateUserEvent(sysUserEvent);
        // 更新关系表
        return true;
    }

    /**
     * 删除事件信息
     *
     * @param id    事件id
     * @param files 事件附件id字符串 使用 , 分割
     * @return
     */
    @Override
    public Boolean deleteEventInfo(Long id, String files) {
        // 将字符串转化为 列表
        String[] split = files.trim().split(",");
        log.debug("files length " + files.length());
        try {
            // 删除文件
            for (String s : split) {
                if (!s.equals("")) {
                    fileService.deleteFile(Long.valueOf(s));
                    log.debug("fileId : " + s + " 被删除 !");
                }
            }
        } catch (NumberFormatException e) {
            log.error(e.getMessage());
            log.error("files : " + files);
            return false;
        }
        // 删除事件表记录
        eventMapper.deleteById(id);
        userEventService.deleteUserEvent(id);
        return true;
    }

    @Override
    public List<SysEvent> getEventInfosByUser(Long userId, String query, List<String> dates) {

        // 先获取用户信息
        SysUser user = userService.getUserById(userId);
        List<SysEvent> sysEvents;

        // 根据时间排序
        // 判断是否参数信息
        // 根据日期添加条件
        String startDate = null;
        String endDate = null;
        if (dates.size() == 2) {
            startDate = dates.get(0);
            endDate = dates.get(1);
        }
        switch (user.getType().intValue()) {
            case RoleType.ADMIN:
            case RoleType.SUPER_ADMIN:
                sysEvents = eventMapper.selectByAdmin(user.getAddress(),query,startDate,endDate);
                break;
            default:
                sysEvents = eventMapper.selectByOther(user.getAddress(),userId,query,startDate,endDate);
                break;
        }
        // 处理附件列表
        getFileByFileId(sysEvents);
        return sysEvents;
    }


    @Override
    public List<SysEvent> getEventByStatus(Long userId, Integer status, String query) {

        List<SysEvent> eventByStatus = eventMapper.getEventByStatus(userId, status, query);
        // 处理附件列表
        getFileByFileId(eventByStatus);
        return eventByStatus;
    }

    private void getFileByFileId(List<SysEvent> eventByStatus) {
        for (SysEvent sysEvent : eventByStatus) {
            HashMap<String, List<String>> files = fileService.getFiles(sysEvent.getFileList());
            sysEvent.setImages(files.get("images"));
            sysEvent.setVideos(files.get("videos"));
        }
    }

    @Override
    public List<SysEvent> getEventByAuthorId(Long authorId) {

        QueryWrapper<SysEvent> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("author_id", authorId);

        try {
            return eventMapper.selectList(queryWrapper);
        } catch (Exception e) {
            e.printStackTrace();
            return new ArrayList<>();
        }
    }

    @Override
    public SysEvent getEventById(Long eventId) {
        SysEvent sysEvent = eventMapper.getEventById(eventId);
        HashMap<String, List<String>> files = fileService.getFiles(sysEvent.getFileList());
        sysEvent.setImages(files.get("images"));
        sysEvent.setVideos(files.get("videos"));
        return sysEvent;
    }

    /**
     * 查询统计
     *
     * @param pageNum
     * @param pageSize
     * @param query
     * @param userId
     * @return
     */
    @Override
    public IPage<EventCountVO> selectCountEvent(Long pageNum, Long pageSize, String query, Long userId) {

        SysUser userById = userService.getUserById(userId);

        Page<EventCountVO> page = new Page<>();
        page.setCurrent(pageNum);
        page.setSize(pageSize);

        try {
           return eventMapper.selectCountEvent(page, userById.getAddress(), query);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
